package net.tycmc.cty.ctyms.timejob.iems.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.configuration.ConfigurationException;

import com.tycmc.functions.util.NumberFormat;

import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DynamicReadConfig;
import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.iems.dao.FuelLevelMonitorDao;

public class FuelLevelMonitorService {
	private FuelLevelMonitorDao flmd;

	public FuelLevelMonitorDao getFlmd() {
		return flmd;
	}

	public void setFlmd(FuelLevelMonitorDao flmd) {
		this.flmd = flmd;
	}
	public void startWork(String workDate) throws ParseException, ConfigurationException{
		//统计日期
		//String workDate=DateUtil.addDay(-1);
		Map<String,Object>param=new HashMap<String,Object>();
		param.put("dateTime",workDate);
		List<Map<String,Object>>listInfo=flmd.getTimingInfoOfFuelLevel(param);
		
		if(null==listInfo||listInfo.size()==0){
			System.out.println("日期："+workDate+" 没有符合条件的数据");
			return;
		}
		String pyuValue=DynamicReadConfig.getConfigProperty("config.properties","pyuValue");
		String syuValue=DynamicReadConfig.getConfigProperty("config.properties","syuValue");
		Map<String,List<Map<String,Object>>>mapInfo=new ListUtil().groupBy("vehicleid",listInfo);
		Map<String,List<Map<String,Object>>>mapTwoInfo=this.getUseFulDate(mapInfo,pyuValue,syuValue);
		Map<String,List<Map<String,Object>>>mapDateInfo=this.getResultDate(mapTwoInfo);
		List<String>sqlList=new ArrayList<String>();
		this.SpellSqlString(mapDateInfo, sqlList, workDate);
		boolean flag=flmd.execBatchSql(sqlList);
		if(flag==true){
			System.out.println("插入成功，插入"+sqlList.size()+"条");
		}else{
			System.out.println("插入失败，应插入"+sqlList.size()+"条");
		}
	}
	/**根据前三条，后三条的过滤原则，获取有效数据
	 * @param mapInfo
	 * @return
	 */
	public Map<String,List<Map<String,Object>>>getUseFulDate(Map<String,List<Map<String,Object>>>mapInfo,String pyuValue,String syuValue){
		Set<String>set=mapInfo.keySet();
		Map<String,List<Map<String,Object>>>mapTwoInfo=new HashMap<String, List<Map<String,Object>>>();
		for(Iterator<String>it=set.iterator();it.hasNext();){
			List<Map<String,Object>>list=new ArrayList<Map<String,Object>>();
			String vehicleid=it.next();
			List<Map<String,Object>>listresult=mapInfo.get(vehicleid);
			for(int i=0;i<listresult.size();i++){
				Map<String,Object>mapresult=listresult.get(i);
				//判断此条“邮箱液位”是否是上升状态
				String msgt_tankchangestate=MapGetter.getString(mapresult,"msgt_tankchangestate");
				if(!"0".equals(msgt_tankchangestate)){//非0即不是上升状态；继续遍历下一条
					continue;
				}
				String tanklevel=MapGetter.getString(mapresult,"tanklevel");
				if("--".equals(tanklevel)){//若值为null 或者没有配置A、B则不处理逻辑
					continue;
				}else{
					//判断i的位置
					 //向前推三条
					double ptvalue=0;//前三条累积值
					double stvalue=0;//后三条累积值
					double avgptvalue=0;//前三条累积值
					double avgstvalue=0;//前三条累积值
					int ptnum=0;
					int stnum=0;
					boolean ptflag=false;//前三条标记
					boolean stflag=false;//后三条标记
					double fuleValue=Double.valueOf(tanklevel);
					for(int pt=i-3;pt<i;pt++){//前三条平均值,有几条算几条
						if(pt>=0){
							ptvalue+=Double.valueOf(MapGetter.getString(listresult.get(pt),"tanklevel"));
							ptnum++;
							if(i-pt==1){//前面三条，最后一条
								ptflag=true;
								avgptvalue=NumberFormat.div(ptvalue/ptnum, 1,2);
							}
						}
					}
					int m=i;
					for(int st=m+1;st<m+4;st++){//前三条平均值,有几条算几条
						if(st<listresult.size()){
							stvalue+=Double.valueOf(MapGetter.getString(listresult.get(st),"tanklevel"));
							stnum++;
							if(m+4-st==1||st==listresult.size()-1){//后面三条最后1条
								stflag=true;
								avgstvalue=NumberFormat.div(stvalue/stnum, 1,2);
							}
						}
					}
					if(ptflag==true){//前面存在有效数据，需要计算
						if(fuleValue<=avgptvalue+Double.valueOf(pyuValue)){//此条无效
							continue;
						}
					}
					if(stflag==true){//后面面存在有效数据，需要计算
						if(fuleValue>=avgstvalue+Double.valueOf(syuValue)){//此条无效效
							continue;
						}
					}
					//此条数据有效
					list.add(mapresult);
				}
			}
			if(list.size()>0){
				mapTwoInfo.put(vehicleid,list);
			}
		}
		return mapTwoInfo;
	}
	/**获取根据时间整合后的逻辑
	 * @param mapInfo
	 * @return
	 * @throws ParseException 
	 */
	public Map<String,List<Map<String,Object>>>getResultDate(Map<String,List<Map<String,Object>>>mapInfo) throws ParseException{
		//获取到有效数据之后，开始根据时间进行合并
		Set<String>set=mapInfo.keySet();
		Map<String,List<Map<String,Object>>>mapinfo=new HashMap<String, List<Map<String,Object>>>();
		for(Iterator<String>it=set.iterator();it.hasNext();){
			String vehicleid=it.next();
			List<Map<String,Object>>listresult=mapInfo.get(vehicleid);
			int numflag=1;
			String beginTime="";
			String endTime="";
			double totalValue=0;
			List<Map<String,Object>>listinfo=new ArrayList<Map<String,Object>>();
			Map<String,Object>map=new HashMap<String, Object>();
			for(Map<String,Object>mapre:listresult){
				if(numflag==1){
					map=mapre;
					beginTime=MapGetter.getString(mapre,"msgt_msgtime");
					endTime=flmd.getdatePlusOneHour(beginTime,1);
					totalValue=Double.valueOf(MapGetter.getString(mapre,"tankchangevalue"));
					listinfo.add(map);
					numflag++;
				}else{
					String msgTime=MapGetter.getString(mapre,"msgt_msgtime");
					double fuelValue=Double.valueOf(MapGetter.getString(mapre,"tankchangevalue"));
					if(flmd.compareDate(beginTime,endTime,msgTime)){//比较时间,时间在上一条的1小时范围内，需要合并
						totalValue+=fuelValue;
						listinfo.remove(listinfo.size()-1);
						map.put("tankchangevalue",totalValue);
						listinfo.add(map);
					}else{
						/*map.put("tankchangevalue",totalValue);
						listinfo.add(map);*/
						beginTime=MapGetter.getString(mapre,"msgt_msgtime");
						endTime=flmd.getdatePlusOneHour(beginTime,1);
						totalValue=Double.valueOf(MapGetter.getString(mapre,"tankchangevalue"));
						map=mapre;
						listinfo.add(map);
					}
				}
			}
			mapinfo.put(vehicleid,listinfo);
		}
		return mapinfo;
	}
	/**
	 * sql开始拼串
	 * @param mapInfo
	 * @return
	 * @throws ParseException
	 */
	public void SpellSqlString(Map<String,List<Map<String,Object>>>mapInfo,List<String>sqlList,String dateTime) throws ParseException{
		//ExecutorService	executorService = Executors.newFixedThreadPool(10);//开一个线程池
		//获取到有效数据之后，开始根据时间进行合并
		Set<String>set=mapInfo.keySet();
		Map<String,List<Map<String,Object>>>mapinfo=new HashMap<String, List<Map<String,Object>>>();
		for(Iterator<String>it=set.iterator();it.hasNext();){
			String vehicleid=it.next();
			List<Map<String,Object>>listresult=mapInfo.get(vehicleid);
			for(Map<String,Object>mapre:listresult){
				String msg_map=MapGetter.getString(mapre,"msg_map");
				String lo=null;
				String la=null;
				if(StringUtil.isValid(msg_map)){
					lo=msg_map.split(",")[0];
					la=msg_map.split(",")[1];
				}
				String sql="insert into fuelLevelMonitorData_"+dateTime.replaceAll("-","").substring(0,8)+"" +
						"(FLMD_VclID,FLMD_msgTime,FLMD_TankChangeValue,FLMD_Lo,FLMD_La,FLMD_StateTime) " +
						"values("+vehicleid+",'"+MapGetter.getString(mapre,"msgt_msgtime")+"',"+MapGetter.getString(mapre,"tankchangevalue")+","+lo+","+la+",'"+dateTime+"')";
				sqlList.add(sql);
			}
		}
	}
}
